package cn.deepmax.spring.cloud.system.sale.controller;

import cn.deepmax.spring.cloud.common.web.AjaxResponse;
import cn.deepmax.spring.cloud.system.sale.entity.Order;
import cn.deepmax.spring.cloud.system.sale.service.OrderService;
import cn.deepmax.spring.cloud.system.sale.vo.AddOrderRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/{id}.json")
    public AjaxResponse getOrder(@PathVariable(name = "id")Long id, HttpServletRequest request){
        Long userId = getCurrentUserId(request);
        Optional<Order> order = orderService.findOrder(userId, id);
        return order.map(o->AjaxResponse.ok(o))
                .orElse(AjaxResponse.fail("No order "+id+" found"));
    }

    @GetMapping("/list.json")
    public AjaxResponse getOrderList(Long productId,String desc,
                                     @RequestParam(required = false, defaultValue = "0") Integer page,
                                     @RequestParam(required = false, defaultValue = "10") Integer size,
                                     HttpServletRequest request){
        Long userId = getCurrentUserId(request);
        Page<Order> orders = orderService.findUserOrders(userId, productId, desc, page, size);
        return AjaxResponse.ok(orders);
    }

    @PostMapping("/add.json")
    public AjaxResponse getOrderList(@Validated @RequestBody AddOrderRequest add, BindingResult bindingResult,
                                     HttpServletRequest request){

        Long userId = getCurrentUserId(request);
        add.setUserId(userId);
        Order order = orderService.addOrder(add);
        return AjaxResponse.ok(order);
    }


    private Long getCurrentUserId(HttpServletRequest request){
        return 1L;
    }


}
